<!-- 项目详情弹窗 -->
<template>
  <el-dialog
    v-model="dialogFormVisible"
    v-loading="detailLoading"
    width="50%"
    draggable
    overflow
    @close="handleClose"
  >
    <template #header>
      <span>项目详情</span>
      <el-button
        v-if="props.type != 'detail'"
        style="float: right"
        size="small"
        color="#1E3485"
        @click="shoepjctSelectDialog()"
        >选择已有项目</el-button
      >
    </template>
    <div class="crossRope" />
    <el-form
      ref="formModelRef"
      style="margin-top: 2%"
      label-width="150px"
      :model="formModel"
      :rules="rules"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item
            label="项目编码"
            required
            style="width: 85%"
            prop="projectCode"
          >
            <el-input
              v-model="formModel.projectCode"
              placeholder="请输入 项目编码"
              :disabled="props.type === 'detail'"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item
            label="项目名称"
            required
            style="width: 85%"
            prop="projectName"
          >
            <el-input
              v-model="formModel.projectName"
              placeholder="请输入 项目名称"
              :disabled="props.type === 'detail'"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item
            label="所属分公司"
            required
            style="width: 85%"
            prop="orgName"
          >
            <el-input
              v-model="formModel.orgName"
              placeholder="请选择 所属分公司"
              :disabled="props.type === 'detail'"
              clearable
              @click="showDeptSelectDialog('org')"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item
            label="采购单位"
            required
            style="width: 85%"
            prop="purchaseDeptName"
          >
            <el-input
              v-model="formModel.purchaseDeptName"
              placeholder="请选择 采购单位"
              :disabled="props.type === 'detail'"
              clearable
              @click="showDeptSelectDialog('pchs')"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="10">
          <el-form-item label="项目所在地">
            <el-select
              v-model="formModel.provinceName"
              placeholder="请选择 省份"
              :disabled="props.type === 'detail'"
            >
              <el-option
                v-for="item in provinceList"
                :key="item.key"
                :label="item.value"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label-width="20">
            <el-select
              v-model="formModel.cityName"
              placeholder="请选择 城市"
              :disabled="props.type === 'detail'"
            >
              <el-option
                v-for="item in cityList"
                :key="item.key"
                :label="item.value"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label-width="20">
            <el-select
              v-model="formModel.districtName"
              placeholder="请选择 地区"
              :disabled="props.type === 'detail'"
            >
              <el-option
                v-for="item in districtList"
                :key="item.key"
                :label="item.value"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="项目地址" style="width: 85%">
            <el-input
              v-model="formModel.projectAddress"
              placeholder="请输入 项目地址"
              :disabled="props.type === 'detail'"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="crossRope" />
    <div style="text-align: right; margin-top: 2%">
      <el-button
        v-if="props.type != 'detail'"
        color="#1E3485"
        :icon="Select"
        size="small"
        @click="submitSave"
        >保存</el-button
      >
      <el-button :icon="CloseBold" size="small" @click="handleClose"
        >关闭</el-button
      >
    </div>
    <div class="dialogs">
      <projectSelectDialog
        :visible="pjctselectDialogVisible"
        @close="closePjctselectDialogVisible"
        @confirm="pjctselectDialogConfirm"
      />
      <deptSelectDialog
        :visible="deptselectDialogVisible"
        @close="closeDeptselectDialogVisible"
        @confirm="deptselectDialogConfirm"
      />
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import { ElDialog, ElMessage } from "element-plus";
import { Select, CloseBold } from "@element-plus/icons-vue";
import projectSelectDialog from "./projectSelectDialog.vue";
import deptSelectDialog from "./deptSelectDialog.vue";
import {
  getProjectInfo,
  getAreaList,
  saveProjectInfo
} from "@/api/ERP_baseMessage";

///////////////////////// 公共 /////////////////////////
// 弹窗关闭/打开
const props = defineProps({
  visible: Boolean,
  type: String,
  projectType: String,
  id: String
});
const dialogFormVisible = ref(false);
const emit = defineEmits(["close", "confirm"]);
function handleClose() {
  for (let key in formModel) {
    formModel[key] = "";
  }
  emit("close", false);
}
watch(
  () => props.visible,
  val => {
    dialogFormVisible.value = val;
  },
  { immediate: true }
);
///////////////////////// 数据准备 /////////////////////////
// 表单数据
let formModel = reactive({
  id: "", // 主键ID
  projectType: "", // 项目类型 1-内部 2-外部
  projectCode: "", // 项目编码
  projectName: "", // 项目名称
  orgId: "", // 所属分公司ID
  orgName: "", // 所属分公司
  purchaseDeptId: "", // 采购单位ID
  purchaseDeptName: "", // 采购单位
  provinceId: "", // 省份ID
  provinceName: "", // 省份
  cityId: "", // 城市ID
  cityName: "", // 城市
  districtId: "", // 区县ID
  districtName: "", // 区县
  projectAddress: "" // 项目地址
});
// 表单校验
const rules = reactive({
  projectCode: [
    { required: true, message: "请输入 项目编码", trigger: "blur" }
  ],
  projectName: [
    { required: true, message: "请输入 项目名称", trigger: "blur" }
  ],
  orgName: [{ required: true, message: "请输入 所属分公司", trigger: "blur" }],
  purchaseDeptName: [
    { required: true, message: "请输入 采购单位", trigger: "" }
  ]
});
// 弹窗加载
let detailLoading = ref(false);
// 省份/城市/地区
let provinceList = ref([]);
let cityList = ref([]);
let districtList = ref([]);
// 地区监听 - 省份
watch(
  () => formModel.provinceName,
  newValue => {
    if (newValue != "") {
      formModel.provinceId = provinceList.value.find(
        item => item.value === formModel.provinceName
      ).key;
      getAreaOption(formModel.provinceId, "city");
    }
  }
);
// 地区监听 - 城市
watch(
  () => formModel.cityName,
  newValue => {
    if (newValue != "") {
      formModel.cityId = cityList.value.find(
        item => item.value === formModel.cityName
      ).key;
      getAreaOption(formModel.cityId, "dsct");
    }
  }
);
// 地区监听 - 地区
watch(
  () => formModel.districtName,
  newValue => {
    if (newValue != "") {
      formModel.districtId = districtList.value.find(
        item => item.value === formModel.districtName
      ).key;
    }
  }
);
///////////////////////// 弹窗类 /////////////////////////
// 选择项目弹窗
let pjctselectDialogVisible = ref(false);
function shoepjctSelectDialog() {
  pjctselectDialogVisible.value = true;
}
function closePjctselectDialogVisible(val: boolean) {
  pjctselectDialogVisible.value = val;
}
const pjctselectDialogConfirm = (data: any) => {
  formModel.id = data.selectedRow.id;
  getInfo();
};
// 选择公司弹窗
let deptselectDialogVisible = ref(false);
let confirmInput = "";
function showDeptSelectDialog(input: string) {
  if (input === "org") {
    confirmInput = "org";
  } else if (input === "pchs") {
    confirmInput = "pchs";
  }
  deptselectDialogVisible.value = true;
}
function closeDeptselectDialogVisible(val: boolean) {
  deptselectDialogVisible.value = val;
}
const deptselectDialogConfirm = (data: any) => {
  if (confirmInput === "org") {
    formModel.orgId = data.selectedRow.id;
    formModel.orgName = data.selectedRow.deptName;
  }
  if (confirmInput === "pchs") {
    formModel.purchaseDeptId = data.selectedRow.id;
    formModel.purchaseDeptName = data.selectedRow.deptName;
  }
  confirmInput = "";
};
// Map转Option
function convertData(data) {
  const result = [];
  for (const key in data) {
    if (data.hasOwnProperty(key)) {
      const region = data[key];
      result.push({ key: key, value: region });
    }
  }
  return result;
}
///////////////////////// 数据请求 /////////////////////////
// 保存
async function submitSave() {
  let params: ApiParams = {};
  for (let key in formModel) {
    params[key] = formModel[key];
  }
  try {
    const response: ApiResponse = await saveProjectInfo(params);
    if (response.code === 200) {
      ElMessage.success("保存成功");
      emit("close");
    } else {
      ElMessage.error("保存失败: " + response.msg);
    }
  } catch (error) {}
}
// 获取详情
async function getInfo() {
  detailLoading.value = true;
  let params: ApiParams = {};
  params.id = formModel.id;
  try {
    const response: ApiResponse = await getProjectInfo(params);
    if (response.code === 200) {
      for (let key in formModel) {
        formModel[key] = response.data[key];
      }
    } else {
      ElMessage.error("获取项目详情失败: " + response.msg);
    }
  } catch (error) {
  } finally {
    detailLoading.value = false;
  }
}
// 获取地区列表
async function getAreaOption(id: string, type: string) {
  let params: ApiParams = {};
  params.parentId = id;
  const response: ApiResponse = await getAreaList(params);
  if (response.code === 200) {
    if (type === "prvc") {
      provinceList.value = convertData(response.data);
    }
    if (type === "city") {
      cityList.value = convertData(response.data);
    }
    if (type === "dsct") {
      districtList.value = convertData(response.data);
    }
  } else {
    ElMessage.error("获取地区数据失败: " + response.msg);
  }
}
///////////////////////// 公共 /////////////////////////
// 获取详情
watch(dialogFormVisible, newValue => {
  if (newValue) {
    formModel.projectType = props.projectType;
    if (props.type && props.type != "add") {
      formModel.id = props.id;
      getInfo();
    }
    getAreaOption("0", "prvc");
  }
});
</script>

<style lang="scss" scoped></style>
